function getHangXiang(dusu, sudu) {
    if (sudu < 0 || dusu == "") return "......";
    var z = 5,
    fz = 10,
    p = 30;
    var hangxiang = lg.hangxiang;
    var qujian1 = [z, fz, fz, p, 90 - p, 90 - z, 90 - fz, 90 + fz, 90 + p, 180 - p, 180 - z, 180 - fz, 180 + fz, 180 + p, 270 - p, 270 - z, 270 - fz, 270 + fz, 270 + p, 360 - p];
    var qujian2 = [360 - z, 360 - fz, p, 90 - p, 90 - fz, 90 + z, 90 + fz, 90 + p, 180 - p, 180 - fz, 180 + z, 180 + fz, 180 + p, 270 - p, 270 - fz, 270 + z, 270 + fz, 270 + p, 360 - p, 360 - fz];
    for (var i = 0; i < qujian1.length; i++) {
        if (i == 0 || i == 1) {
            if (qujian2[i] <= dusu || dusu <= qujian1[i])
            return hangxiang[i];
        } else {
            if (qujian1[i] <= dusu && dusu <= qujian2[i])
            return hangxiang[i];
        }
    }
    return dusu;
}
function parseGt06Staust(val) {
    var val = val + "";
    if ((typeof val) == "undefined") return lg.sdw0;
    var stem = parseInt(val.substr(0, 2), 16);
    var tem = stem.toString(2);
    if (tem.length < 7 || (tem.length == 7 && tem.substr(0, 1) == "0") || (tem.length == 8 && tem.substr(1, 1) == "0")) return lg.sdw0;
    else return lg.sdw1;
}
document.onmousemove = mouseCoords;
function mouseCoords(ev) {
    ev = ev || window.event;
    if (ev.pageX || ev.pageY) {
        mousePos = {
            x: ev.pageX,
            y: ev.pageY
        };
    }
    mousePos = {
        x: ev.clientX + document.documentElement.scrollLeft - document.documentElement.clientLeft + 20,
        y: ev.clientY + document.documentElement.scrollTop - document.documentElement.clientTop + 20
    };
}
function WarnsTimely(uid, timelyUrl, mds, updateUrl,remotUrl) {
    this.id = uid;
    this.remotUrl = remotUrl;
	this.updateUrl = updateUrl;
	this.timelyUrl = timelyUrl;
    this.mds = mds;
    this.FIRST_LOAD_DATAS = false;
    this.interval = "-1";
    this.LAY_FLAG_MAX_MIN = true;
    this.MAX_ID = 0;
    this.MAIN_TIMER = "-1";
    this.filterObj = ''; //过滤报警类型
	this.actionSave = true;//缓存当前的声音报错设置 默认取消显示声音：0；
	this.isDealer = (typeof(haseChildSchoolBack)!=='undefined' && haseChildSchoolBack) ||
		window.location.href.toString().toLowerCase().indexOf('/dealer')> 0;
	//this.isDealer = window.location.href.toString().toLowerCase().indexOf('/dealer')> 0;
	//暂不使用cookie，监控页面默认开启报警声音，经销商页面默认不开启
    this.VOICE_FLAG = location.href.indexOf('main.html')>-1?true:false;
    var cDiv = document.createElement("div"), voiceDiv = document.createElement('div'),
		    mapDiv = document.createElement("div"),strHtml = [];
	document.body.appendChild(cDiv);
	document.body.appendChild(voiceDiv);
	document.body.appendChild(mapDiv);

    strHtml.push('<div style="background:#EBEBEB;height:20px;line-height:20px;margin:1px;cursor:pointer;">');
    strHtml.push('<div style="float:left;padding-left:5px;font-weight:bold;width:324px;">' + lg.warnTips + '');
    strHtml.push('<span style="margin-left:5px;"><label><input ');
    strHtml.push(alarmSound?'checked':'');
    strHtml.push(' type="checkbox" id="chk_voiceItem" onclick="timeWarnOBJ.voiceItem(this.checked);" />');
    strHtml.push('<span style="color:#669;">' + lg.warnVoice + '</span></label></span><em style="font-style:normal;margin:0 10px 0 10px;color:#bbb;">|</em>');
    //加入报警类型过滤lg.wtype ,iE7把\0当做结束符号来处理，需要转义一次
    strHtml.push('<span style="color:#669;*margin-top:2px;+margin-top:2px;margin-top:2px\\0;" class="filter-warn">' + lg.filterWarnType + '</span></div>');
    strHtml.push('<span style="float:right;width:32px;height:15px;">');
    strHtml.push('<label style="float:left;width:15px;height:15px;cursor:pointer;background:url(');
    var imgUri = (typeof LOGIN_SITE!='undefined')?LOGIN_SITE+'/user/':'';
    strHtml.push(imgUri);
    strHtml.push('images/iw_min.gif) no-repeat;background-position:bottom;" id="tomin">&nbsp;</label>');
    strHtml.push('<label style="float:left;width:15px;height:15px;cursor:pointer;background:url(',imgUri,'images/iw_max.gif) no-repeat;background-position:bottom;" id="tomax">&nbsp;</label>');
    strHtml.push('</span></div><div id="noticecon" style="height:130px;overflow-y:scroll;margin:1px;float:left;width:100%;"></div></div>');

	voiceDiv.id = "message_voice";
    mapDiv.id = "mapDIV";
	mapDiv.style.cssText = 'width:300px;height:260px;position:absolute;overflow:hidden;z-index:999;border:#CCC 1px solid;display:none;';
	cDiv.id = "newnotice";
	cDiv.style.cssText = 'position:absolute;width:650px;border:solid #999 1px;background-color:#fff;display:none;font-size:12px;z-index:990;';
    cDiv.innerHTML = strHtml.join("");
	$(cDiv.children[0]).click(function(e){
		if(e.target.tagName =='DIV'){
			var list = this.nextSibling;
			if(list.style.display!='none'){
				$("#tomin").click();
			}else{
				$("#tomax").click();
			}
		}
	});
	//打开过滤报警面板
	var _this = this;
	$(cDiv.children[0]).find('.filter-warn').click(function(e){
		e.stopPropagation();
		var cookies = _this.filterObj;	//_.cookie('alarmTypeFilter');
		var warnFilterNodeStr = [];
		for(var index in lg.wtype){
			//去掉超速，栅栏，离线报警选择
		   if(index != 5 && index != 6 && index != 7){
			 warnFilterNodeStr.push('<li style="margin:5px;width:160px;display:block;float:left;overflow:hidden;" index="',index,
					'"><label><input type="checkbox" ',
					index == 0?' disabled ':(cookies.indexOf(','+index+',')<0?'checked="checked"':''),
					' />',lg.wtype[index],'</label></li>');
			}
		}
		var ul = document.createElement('div');
		ul.innerHTML = '<div><div style="font-weight:bold;font-size:12px;color:#555;margin:5px 0 5px 5px;">'+lg.filterWarnTip[0]+
		'<img style="margin-left:10px;" src="http://www.gpsoo.net/dealer/images/qas.png" title="'+
		lg.filterWarnTip[1]+'" /></div><ul style="margin:0 0 0 5px;padding:0;">'+warnFilterNodeStr.join('')+'</ul></div>';
		//将过滤的报警类型写入cookie，值为',0,1,10,'
		$(ul).find('input').click(function(){
			var val = [];
			$(this).parents('ul').eq(0).find('input').each(function(){
				if(!this.checked){
					val.push($(this.parentNode.parentNode).attr('index'));
				}
			});
			//_.cookie('alarmTypeFilter',','+val.join(',')+',',{expires:365,path:'/'});
			_this.filterObj = ',' + val.join(',') + ',';
		});
		win.setTitle(lg.filterWarnType);
		win.setWH(360,180);
		win.setContent(ul);
		win.show();
	});
};
WarnsTimely.prototype.loadDataById = function() {
    _.ajax.jsonp((_.net['loadDataById_current_server'] || timeWarnOBJ.timelyUrl) + '/GetDataService',{
    	method:'queryLocalAlarmInfoUtc', callback:'timeWarnOBJ.loadDataCallBack', school_id:timeWarnOBJ.id,
    	mds:timeWarnOBJ.mds, max_id:timeWarnOBJ.MAX_ID
    });
};
WarnsTimely.prototype.loadDataCallBack = function(obj) {
    if (obj.success) {
		var head = document.head || document.getElementsByTagName('head')[0],len = head.children.length;
        if (obj.rows.length > 0) {
            if (!timeWarnOBJ.FIRST_LOAD_DATAS) {
                timeWarnOBJ.FIRST_LOAD_DATAS = true;
                timeWarnOBJ.messageWinListener();
                timeWarnOBJ.createDatagrid(obj.rows);
            } else {
                if (!timeWarnOBJ.LAY_FLAG_MAX_MIN) {
                    $("label[id=tomax]").click();
                }
                timeWarnOBJ.updateDatagrid(obj.rows);
            }
            var warnInfo = 0, 
            	filterTypes = this.filterObj;//_.cookie('alarmTypeFilter')
            for(var index in obj.rows){
            	if(filterTypes.indexOf(','+obj.rows[index].type_id+',') == -1)
        		{
            		//只要找到一条没有过滤掉就开始报警
            		warnInfo += 1;
            		break;
        		}
            }
            //开启报警且报警信息没有被过滤掉
            if (timeWarnOBJ.VOICE_FLAG && alarmSound && warnInfo) {
				_('message_voice').innerHTML = ('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="1" height="1"><param name="movie" value="'+
            			this.remotUrl+'/user/sound.swf" /><param name="quality" value="high" /><embed src="'+
            			this.remotUrl+'/user/sound.swf" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="1" height="1"></embed></object>');
			}
		}
    }
};
WarnsTimely.prototype.createDatagrid = function(rows) {
    var html = [],isdealer = this.isDealer, warnTypeCookie = this.filterObj;//_.cookie('alarmTypeFilter')
    html.push('<table style="width:631px;" border="0" cellspacing="1" cellpadding="0">');
    html.push('<thead>');
    html.push('<tr style="background:#F5F5F5;" >');
    html.push('<td align="center" height="22">' + lg.pro + lg.name + '</td>');
    html.push('<td align="center">' + lg.warn + lg.type + '</td>');
    html.push('<td align="center">' + lg.warn + lg.time + '</td>');
    html.push('<td align="center">' + lg.dwtime + '</td>');
    html.push('<td align="center">' + lg.speed + '(km/h)</td>');
    html.push('<td align="center">' + lg.course + '</td>');
    html.push('<td align="center">' + lg.sdw + '</td>');
    html.push('<td align="center">' + lg.operate + '</td>');
    html.push('</tr></thead><tbody id="warnTab">');
    var rowsLen = rows.length;
    for (var i = rowsLen -1; i >-1; i--) {
        if (rows[i].id > timeWarnOBJ.MAX_ID) timeWarnOBJ.MAX_ID = rows[i].id;
        var warnTypeId = rows[i].type_id;
    	//被过滤则不显示
    	if(warnTypeCookie.indexOf(','+warnTypeId+',')>-1)
    		continue;
        html.push('<tr style="text-align:center;cursor:pointer;" rowdata="');
		html.push(rows[i].id);
		html.push('" userid="');
		html.push(rows[i].user_id);
        html.push('"><td align="center" height="22">' + rows[i].user_name + '</td>');
        html.push('<td align="center">' + lg.wtype[warnTypeId] + '</td>');
        html.push('<td align="center">' + utcToLocal(rows[i].send_time) + '</td>');
        html.push('<td align="center">' + utcToLocal(rows[i].gps_time) + '</td>');
        html.push('<td align="center">' + rows[i].speed + '</td>');
        html.push('<td align="center">' + getHangXiang(rows[i].course, rows[i].speed) + '</td>');
        html.push('<td align="center">' + parseGt06Staust(rows[i].gps_status) + '</td>');
        html.push('<td align="center"><span style="cursor:pointer;color:#069;">' + lg.warnDealWith[rows[i].status] + '</span>&nbsp;');
        //html.push('<span style="cursor:pointer;color:#069;" onmouseout="timeWarnOBJ.hidePositionMap();" onclick="timeWarnOBJ.viewPositionMap(' + rows[i].weidu + ',' + rows[i].jingdu + ')">' + lg.p1 + '</span></td>');
        html.push('</td>');
        html.push('</tr>');
    }
    html.push('</tbody>');
    html.push('</table>');
    $("#noticecon").html(html.join("")).find('#warnTab>tr').each(function(){
		bindRowEvent(this, isdealer);
	});
    //$("#mapDIV").html('<iframe name="mapiframe" id="mapiframe" onMouseOver="clearInterval(timeWarnOBJ.interval);" onMouseOut="timeWarnOBJ.hidePositionMap();" src="../map-abc.jsp?lat=22.573978188551297&lng=113.92078757286072" style="width:300px;height:260px;" scrolling="no" frameborder="0"></iframe>');
};
//绑定行的事件
function bindRowEvent(tr,isdealer){
	//弹窗查看设备信息
	$(tr).click(function(){
		var deviceName = this.children[0].innerHTML;
		//是经销商页面，转向searchProduct.jsp
		if(window.location.href.toString().toLowerCase().indexOf('/dealer')> -1 && win){
			win.openWinLayer(lg.pro+ lg.search,timeWarnOBJ.remotUrl + '/dealer/searchProduct.jsp?school_id='+window.custId+
				'&info='+encodeURIComponent(deviceName)+'&infuse=1&parent=dealer',700,480,2,window,null);
		}
		//是监控页面
		else{
			//是经销商
			if(haseChildSchoolBack){
				//TODO 客户端暂时不提供此功能
				if(typeof(IS_CLIENT)!='undefined' && IS_CLIENT == false)
					win.openWinLayer(lg.pro+ lg.search,timeWarnOBJ.remotUrl+'/dealer/searchProduct.jsp?school_id='+loginCustId+
							'&info='+encodeURIComponent(deviceName)+'&infuse=1&parent=monitor',700,480,2,window,null);
			//是终端用户
			}else{
				if(typeof pageMenuShow == 'function')
					pageMenuShow('HOME',null);
				//直接定位到地图
				if(GFRAME && GFRAME.selectUser){
					GFRAME.selectUser($(this).attr('userid'));
				}
			}
		}
	}).mouseover(function(){
		this.style.backgroundColor="#fafafa";
	}).mouseout(function(){
		this.style.backgroundColor='#fff';
	}).find('span').click(function(e){
		e.stopPropagation();
		timeWarnOBJ.warnDealWith(this.parentNode,$(this.parentNode.parentNode).attr('rowdata'),1);
	});
}
WarnsTimely.prototype.createDataList = function(rows, id, win) {
    var _container = win.document.getElementById(id);
    if (rows.length == 0) {
        _container.innerHTML = '<div style="border-bottom:1px solid #eeeeee;height:25px;line-height:25px;text-align:center;color:#ff0000;">' + top.lg.nodata + '</div>';
        return;
    }
    var html = [],warnTypeCookie = this.filterObj;//_.cookie('alarmTypeFilter');
    html.push('<table id="datalist" width="100%" border="0" cellspacing="0" cellpadding="2" class="tab">');
    html.push('<thead>');
    html.push('<tr>');
    html.push('<th class="first">' + lg.num + '</td>');
    html.push('<th>' + lg.pro + lg.name + '</th>');
    html.push('<th>' + lg.warn + lg.type + '</th>');
    html.push('<th>' + lg.warn + lg.time + '</th>');
    html.push('<th>' + lg.dwtime + '</th>');
    html.push('<th>' + lg.speed + '(km/h)</th>');
    html.push('<th>' + lg.course + '</th>');
    html.push('<th>' + lg.sdw + '</th>');
    html.push('<th>' + lg.operate + '</th>');
    html.push('</tr></thead><tbody>');
    for (var i = 0; i < rows.length; i++) {
    	var warnTypeId = rows[i].type_id;
    	//被过滤则不显示
    	if(warnTypeCookie.indexOf(','+warnTypeId+',')>-1)
    		return;
        html.push('<tr style="font-weight:' + (rows[i].status == 0 ? 'bold' : 'normal') + ';" class="');
		html.push(i%2==0?'even':'odd');
        html.push('"><td>' + (win.start + i) + '</td>');
        html.push('<td>' + rows[i].user_name + '</td>');
        html.push('<td>' + lg.wtype[warnTypeId] + '</td>');
        html.push('<td>' + utcToLocal(rows[i].send_time) + '</td>');
        html.push('<td>' + utcToLocal(rows[i].gps_time) + '</td>');
        html.push('<td>' + rows[i].speed + '</td>');
        html.push('<td>' + getHangXiang(rows[i].course, rows[i].speed) + '</td>');
        html.push('<td>' + parseGt06Staust(rows[i].gps_status) + '</td>');
        if (rows[i].status == "0") {
            html.push('<td><span><a href="javascript:void(0);" onclick="window.timeWarnOBJ.warnDealWith(this.parentNode,\'' + rows[i].id + '\',0)">' + lg.warnDealWith[rows[i].status] + '</a></span>&nbsp;');
        } else {
            html.push('<td>' + lg.warnDealWith[rows[i].status] + '&nbsp;');
        }
        //html.push('<a href="javascript:void(0);" onclick="top.timeWarnOBJ.viewPositionForList(' + rows[i].weidu + ',' + rows[i].jingdu + ')">' + lg.p1 + '</a>');
        html.push('</td>');
        html.push('</tr>');
    }
    html.push('</tbody>');
    html.push('</table>');
    _container.innerHTML = html.join("");
	$(_container).find('tbody>tr').mouseover(function(){
		$(this).addClass('highlight');
	}).mouseout(function(){
		$(this).removeClass('highlight');
	});
};
WarnsTimely.prototype.updateDatagrid = function(rows) {
    var table = document.getElementById("warnTab");
    for (var i =rows.length -1; i >=0; i--) {
        if (rows[i].id > timeWarnOBJ.MAX_ID) timeWarnOBJ.MAX_ID = rows[i].id;
    	var warnTypeId = rows[i].type_id, warnTypeCookie = this.filterObj;//_.cookie('alarmTypeFilter');
    	//被过滤则不显示
    	if(warnTypeCookie.indexOf(','+warnTypeId+',')>-1)
    		continue;
        var tr = table.insertRow(0);
		tr.setAttribute('rowdata',rows[i].id);
		tr.setAttribute('userid',rows[i].user_id);
		_.css(tr,'text-align: center; cursor: pointer; background-color: rgb(255, 255, 255);');
        var obj = [rows[i].user_name, lg.wtype[rows[i].type_id], utcToLocal(rows[i].send_time), utcToLocal(rows[i].gps_time), rows[i].speed, getHangXiang(rows[i].course, rows[i].speed), parseGt06Staust(rows[i].gps_status)];
        for (var j = 0; j < 7; j++) {

            var _td = document.createElement('td');
            _td.style.textAlign = "center";
            _td.style.height = "22px";
            tr.appendChild(_td);
            _td.appendChild(document.createTextNode(obj[j]));
        }
        var tdDeal = document.createElement('td');
        tdDeal.style.textAlign = "center";
        tr.appendChild(tdDeal);
        var dealHref = "<span style='cursor:pointer;color:#069;'>" + lg.warnDealWith[rows[i].status] + "</span>";
        tdDeal.innerHTML = dealHref;
		if(table.childNodes.length>50){
			_.dom.remove(table.lastChild);
		}
		bindRowEvent(tr,this.isDealer);
    }
};
WarnsTimely.prototype.warnDealWith = function(node, wid, flag) {
    var url = timeWarnOBJ.updateUrl + "/GetDataService?method=processAlarmMessage&callback=timeWarnOBJ.warnDealCallBack"+
    "&id=" + wid + "&mds=" + timeWarnOBJ.mds + "&operator=" + timeWarnOBJ.id;
    _.ajax.jsonp(url);
    if (flag == 1) {
        var tr = node.parentNode;
        tr.style.display = "none";
    } else {
        $(node).html(lg.warnDealWith[1]);
    }
};
WarnsTimely.prototype.voiceItem = function(checked) {
	timeWarnOBJ.actionSave = checked;
	var _flag = checked ? 1 : 0;
	var url = '/GetDataService?method=modifyEnterpriseExtend&callback=timeWarnOBJ.saveAlarmSoundCallBack&id='+timeWarnOBJ.id+'&alarmSound='+_flag;
	_.ajax.jsonp(url);
};
WarnsTimely.prototype.saveAlarmSoundCallBack = function(obj){
	if(obj.success){
		if(timeWarnOBJ.actionSave){
			alarmSound = true;
			$("#chk_voiceItem").attr('checked',true);
		} else {
			alarmSound = false;
			$("#chk_voiceItem").attr('checked',false);
			$("#message_voice").empty();
		}
	}else{//保存失败
		if(timeWarnOBJ.actionSave){
			$("#chk_voiceItem").attr('checked',false);
		} else {
			$("#chk_voiceItem").attr('checked',true);
		}
	}
}

WarnsTimely.prototype.warnDealCallBack = function(obj) {
    if (obj.success) {}
};
WarnsTimely.prototype.viewPositionMap = function(wd, jd) {
    if (timeWarnOBJ.interval != "-1") clearInterval(timeWarnOBJ.interval);
    var mapDiv = document.getElementById("mapDIV");
    mapDiv.style.width = "300px";
    mapDiv.style.height = "260px";
    mapDiv.style.top = (mousePos.y - 290) + "px";
    mapDiv.style.left = (mousePos.x - 330) + "px";
    $("#mapDIV").fadeIn("slow");
    window.frames['mapiframe'].updateMarker(wd, jd);
};
WarnsTimely.prototype.viewPositionForList = function(wd, jd) {
    win.openWinLayer(top.lg.viewpos, "../map-abc.jsp?lat=" + wd + "&lng=" + jd, 300, 283, 2, window, null);
};
WarnsTimely.prototype.hidePositionMap = function() {
    if (timeWarnOBJ.interval != "-1") clearInterval(timeWarnOBJ.interval);
    timeWarnOBJ.interval = setInterval(function() {
        $("#mapDIV").fadeOut("slow");
        clearInterval(timeWarnOBJ.interval);
    },
    1000);
};
WarnsTimely.prototype.messageWinListener = function() {
    $("#newnotice").css({
        "right": "0px",
        "bottom": "0px"
    }).slideDown("slow");
    $("#tomin").click(function(){
    	$("#newnotice").animate( {width: '450px'},200);
        $("#noticecon").slideUp("fast");
        timeWarnOBJ.LAY_FLAG_MAX_MIN = false;
    });
    $("label[id=tomax]").click(function(){
    	$("#newnotice").animate( {width: '650px'},200);
        $("#noticecon").slideDown("fast");
        timeWarnOBJ.LAY_FLAG_MAX_MIN = true;
    });
};
WarnsTimely.prototype.timer = function(seconds) {
    timeWarnOBJ.MAIN_TIMER = setInterval(function() {
        timeWarnOBJ.loadDataById();
    },
    seconds);
};
WarnsTimely.prototype.clearTimer = function() {
    if (timeWarnOBJ.MAIN_TIMER != "-1") {
        clearInterval(timeWarnOBJ.MAIN_TIMER);
    }
};
//将后台utc时间毫秒转为本地时间
function utcToLocal(utc){
	if(isNaN(Number(utc))) return utc;
	var t = new Date(Number(utc));
	d = [t.getFullYear(), t.getMonth()+1, t.getDate()].join('/');
	var mm = t.getMinutes() , ss = t.getSeconds();
	d += ' ' + ([t.getHours(), mm > 9 ? mm : '0'+mm, ss > 9 ? ss : '0'+ss].join(':'));
	return d;
}